﻿using Microsoft.EntityFrameworkCore;
using TuLing.Dto;
using TuLing.Entities;
using TuLing.IServices;

namespace TuLing.Services
{
    public class RBACRolePermissionService: BaseService, IRBACRolePermissionService
    {
        public RBACRolePermissionService(DefaultDbContext context) : base(context) { }

        public async Task AssignPermissionsAsync(RolePermissionDto input)
        {
                var old = _context.RolePermissions.Where(u => u.RoleId == input.RoleId);
                _context.RolePermissions.RemoveRange(old);

                var list = new List<RolePermission>();
                foreach (var id in input.PermissionIds)
                {
                    list.Add(new RolePermission
                        {
                            RoleId = input.RoleId,
                            PermissionId = id 
                        }
                    );
                }
                _context.RolePermissions.AddRange(list);
                await _context.SaveChangesAsync(); 
        }

        public async Task<List<long>> GetPermissionIds(long roleId)
        {
            return await _context.Roles
                           .Where(u => u.Id == roleId)
                           .SelectMany(r => r.RolePermissions)
                           .Select(rp => rp.Permission)
                           .Select(i => i.Id).ToListAsync();
        }
        
    }
}
